import { _decorator, Component, Node, UITransform, view, View } from 'cc';
import { Battle } from './Battle';
const { ccclass, property } = _decorator;

@ccclass('Camera')
export class Camera extends Component {

    protected onLoad(): void {
        Battle.Camera = this.node;
    }
    start() {
    }

    update(deltaTime: number) {
        this.cameraFollowPlayer();
    }
    // 相机跟随player
    cameraFollowPlayer() {
        const cameraPos = this.node.getPosition(); //相机的位置
        const newPos = Battle.playerNode.parent.getPosition(); //新的位置
        // const cameraSize = {
        //     width: 720,
        //     height: 1280
        // }
        const cameraSize = view.getVisibleSize();
        // x轴极限值
        const xMin = -(Battle.MapNode.getComponent(UITransform).width / 2 - cameraSize.width / 2);
        const xMax = Battle.MapNode.getComponent(UITransform).width / 2 - cameraSize.width / 2;
        // y轴极限值
        const yMin = -(Battle.MapNode.getComponent(UITransform).height / 2 - cameraSize.height / 2);
        const yMax = Battle.MapNode.getComponent(UITransform).height / 2 - cameraSize.height / 2;

        if (Battle.playerNode.parent.getPosition().x < xMin || Battle.playerNode.parent.getPosition().x > xMax) {
            newPos.x = cameraPos.x;
        } if (Battle.playerNode.parent.getPosition().y < yMin || Battle.playerNode.parent.getPosition().y > yMax) {
            newPos.y = cameraPos.y;
        }

        // player是否存在且是否可以调用（没有被销毁）
        if (Battle.playerNode.parent && Battle.playerNode.parent.isValid) {
            this.node.setPosition(newPos);
        }
    }
}


